//
//  AddLookViewController.m
//  Manager
//
//  Created by 彭凯敏 on 15/8/18.
//  Copyright (c) 2015年 52xiaoluo. All rights reserved.
//

#import "AddLookViewController.h"
#import "SearchCell.h"
#import "SearchViewController.h"
@interface AddLookViewController ()<searchDelegate>
{
    NSArray *tfArray;
}
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
@property (weak, nonatomic) IBOutlet UIView *contentView;

@property (weak, nonatomic) IBOutlet UITextField *nameTF;
@property (weak, nonatomic) IBOutlet UISegmentedControl *sexSeg;
@property (weak, nonatomic) IBOutlet UITextField *professionTF;
@property (weak, nonatomic) IBOutlet UITextField *phoneTF;

//timePicker

- (IBAction)clickTimeView:(UITapGestureRecognizer *)sender;

@property (weak, nonatomic) IBOutlet UIView *liveTimeView;
@property (weak, nonatomic) IBOutlet UILabel *liveTimeLabel;//入住时间

@property (weak, nonatomic) IBOutlet UILabel *viewTimeLabel;

@property (weak, nonatomic) IBOutlet UIView *timeView;
@property (strong, nonatomic) IBOutlet UIView *pickView;
@property (weak, nonatomic) IBOutlet UIDatePicker *datePicker;
- (IBAction)dateChanged:(UIDatePicker *)sender;
- (IBAction)clickPickSure:(UIButton *)sender;
@property (strong, nonatomic) UIView *currentView;


@property (weak, nonatomic) IBOutlet UITextField *room1TF;
@property (weak, nonatomic) IBOutlet UILabel *roomStatus1;
@property (weak, nonatomic) IBOutlet UITextField *room2TF;
@property (weak, nonatomic) IBOutlet UILabel *roomStatus2;
@property (weak, nonatomic) IBOutlet UITextView *textView;

- (IBAction)clickAdd:(UIButton *)sender;


//search
@property (strong, nonatomic) UITableView *searchTableView;
@property (strong, nonatomic) NSMutableArray *searchDataArray;
@property (strong, nonatomic) NSMutableArray *roomArray;
@property (strong, nonatomic) UITextField *currentTF;

@end

@implementation AddLookViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _roomArray = [[NSMutableArray alloc]initWithObjects:@"",@"", nil];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(requestSuccess:) name:CMD_ViewRoom_AddViewReq object:nil];
    
    [self baseCtlSetTitle:@"添加看房信息"];
    
    [self resetUI];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
}
- (void)resetUI
{
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(scrollViewTap:)];
    [_scrollView addGestureRecognizer:tap];
    [_contentView setSizeWidth:ScreenWidth];
    _scrollView.contentSize = CGSizeMake(ScreenWidth, _contentView.sizeHeight);
    
    [_scrollView addSubview:_contentView];
}
//当键盘出现或改变时调用
- (void)keyboardWillShow:(NSNotification *)aNotification
{
    [self clickPickSure:nil];
    //获取键盘的高度
    NSDictionary *userInfo = [aNotification userInfo];
    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [aValue CGRectValue];
    int height = keyboardRect.size.height;
    
    if (![_textView isFirstResponder]) {
        return;
    }
    //    UITextField *textField = aNotification.object;
    
    [UIViewCategory offsetText:_textView Height:height Super:_scrollView];


}

- (void)keyboardWillHide:(NSNotification *)aNotification
{
    
    
}
#pragma mark - request
- (void)AddViewReq
{
    AddViewReqBuilder *builder = [[AddViewReqBuilder alloc]init];
    [builder setName:_nameTF.text];
    [ builder setGender:_sexSeg == 0?@"男":@"女" ];
    [builder setPhone:_phoneTF.text];
    [builder setJob:_professionTF.text];
    
    [builder setViewTime:[[KMGetDate timespFromTimeStr:_viewTimeLabel.text andFormatter:@"yyyy/MM/dd HH:mm"] longLongValue]*1000];
    
    [builder setCheckInDays:[KMGetDate timespFromTimeStr:_liveTimeLabel.text andFormatter:@"yyyy/MM/dd HH:mm"]];
    
    
    [builder setViewStewardId:[[UserLogic shareInstance]getUserId]];
    [builder setRemark:_textView.text];
    
    
    for (NSInteger i =0;i<_roomArray.count;i++) {
        id object = _roomArray[i];
        if ([object isKindOfClass:[NSString class]]) {
            [_roomArray removeObject:object];
        }
    }
    
    if (_roomArray.count == 0) {
        FailedShow(@"请输入正确的房源信息");
        return;
    }
    
    [builder setViewRoomsArray:_roomArray];
    
    
    [[ViewRoomLogic shareInstance]addViewReqWithBuild:builder.build];
}
- (void)RoomSearchReqWithtext:(NSString *)text
{
    RoomSearchReqBuilder *builder = [[RoomSearchReqBuilder alloc]init];
    RoomFilterBuilder *filter = [[RoomFilterBuilder alloc]init];
    [filter setName:text];
    
    [builder setRoomFilter:filter.build];
    
    [[ViewRoomLogic shareInstance]roomSearchReqWithBuild:builder.build];
    
}
- (void)requestSuccess:(NSNotification *)noti
{
    dispatch_async(dispatch_get_main_queue(), ^{
    
        if ([noti.name  isEqualToString: CMD_ViewRoom_AddViewReq]) {
            if ([noti.object isKindOfClass:[ErrorModel class]])
            {
                ErrorModel *model = noti.object;
                [UIViewCategory FailShowWith:model];
            }
            else
            {
                SuccessShow(@"添加成功");
                [self.navigationController popToRootViewControllerAnimated:YES];
            }
            
        }

        
    });
    
}
#pragma mark - UIScrollViewDelegate
- (void)searchSelectRoom:(RoomInfo *)info
{
    _currentTF.text = info.name;
    if (_currentTF == _room1TF) {
        [_roomArray replaceObjectAtIndex:0 withObject:info];
        _roomStatus1.text = [UIViewCategory roomStatusWith:info];
    }
    if (_currentTF == _room2TF) {
        [_roomArray replaceObjectAtIndex:1 withObject:info];
        _roomStatus2.text = [UIViewCategory roomStatusWith:info];
    }
    _currentTF = nil;
}
- (void)searchNoRoom
{
    _currentTF.text = @"";
    if (_currentTF == _room1TF) {
        [_roomArray replaceObjectAtIndex:0 withObject:@""];
        _roomStatus1.text = @"";
    }
    if (_currentTF == _room2TF) {
        [_roomArray replaceObjectAtIndex:1 withObject:@""];
        _roomStatus2.text = @"";
    }
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{

    [self.view endEditing:YES];
}

#pragma mark - UITextFieldDelegate

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    if (textField == _room1TF || textField == _room2TF) {
        _currentTF = textField;
        
        SearchViewController *search = [[SearchViewController alloc]init];
        
        search.searchStr = textField.text;
        search.delegate = self;
        
        [self.navigationController pushViewController:search animated:YES];
        
    }
    return  YES;
}


- (void)scrollViewTap:(UITapGestureRecognizer *)tap
{
    [self.view endEditing:YES];
    
    if (_scrollView.contentOffset.y > _contentView.sizeHeight - _scrollView.sizeHeight) {
        
        [UIView animateWithDuration:0.25 animations:^{
            [self .scrollView setContentOffset:CGPointMake(0, _contentView.sizeHeight - _scrollView.sizeHeight)];
        }];
        
    }
    
    _currentTF = nil;
    
}



#pragma mark - events
- (IBAction)clickAdd:(UIButton *)sender {
    if ([_nameTF.text isEqualToString:@""]) {
        FailedShow(@"请填写姓名");
        return;
    }
    if ([_professionTF.text isEqualToString:@""]) {
        FailedShow(@"请填写职业");
        return;
    }
    if ([KMCheckTel checkTel:_phoneTF.text] == NO) {
        FailedShow(@"请填写正确的手机号");
        return;
    }
    if ([_liveTimeLabel.text isEqualToString:@""]) {
        FailedShow(@"请输入入住时间");
        return;
    }
    if ([_viewTimeLabel.text isEqualToString:@""]) {
        FailedShow(@"请输入约看时间");
        return;
    }
    if ([_room1TF.text isEqualToString:@""]&&[_room2TF.text isEqualToString:@""]) {
        FailedShow(@"请输入房源信息");
        return;
    }
    
    [self AddViewReq];
    
}
- (IBAction)clickTimeView:(UITapGestureRecognizer *)sender{
    [self .view endEditing:YES];
    _datePicker.minimumDate = [NSDate date];
    
    _currentView = sender.view;
    if (_currentView == _liveTimeView) {
        [_datePicker setDatePickerMode:UIDatePickerModeDate];
        if (![_liveTimeLabel.text isEqualToString:@""]) {
            [_datePicker setDate:[KMGetDate dateFromTimeStr:_liveTimeLabel.text andFormatter:@"yyyy/MM/dd"] animated:YES];
        }
    }
    else if (_currentView == _timeView) {
        [_datePicker setDatePickerMode:UIDatePickerModeDateAndTime];
        if (![_viewTimeLabel.text isEqualToString:@""]) {
            [_datePicker setDate:[KMGetDate dateFromTimeStr:_viewTimeLabel.text andFormatter:@"yyyy/MM/dd HH:mm"] animated:YES];

        }
    }
    

    
    [UIViewCategory offsetText:_currentView Height:IS320?225:280 Super:_scrollView];

    
    if (_pickView.originY == ScreenHeight-64-_pickView.sizeHeight) {
        return;
    }
    
    [_pickView setOriginY:ScreenHeight-64];
    [_pickView setSizeWidth:ScreenWidth];
    [_pickView setSizeHeight:IS320?225:280];
    [self.view addSubview:_pickView];
    [UIView animateWithDuration:0.3 animations:^{
        
        [_pickView setOriginY:ScreenHeight-64-_pickView.sizeHeight];
    }];
    
    
    
}
- (IBAction)dateChanged:(UIDatePicker *)sender {

    NSString *timeStr;
    if (_currentView == _liveTimeView) {
        timeStr = [self stringFromYearDate:sender.date];
        _liveTimeLabel.text = timeStr;
    }
    else if (_currentView == _timeView) {
        timeStr = [self stringFromDate:sender.date];
        _viewTimeLabel.text = timeStr;
    }

    
    
    
}


- (IBAction)clickPickSure:(UIButton *)sender {
    [self dateChanged:_datePicker];
    
    [UIView animateWithDuration:0.3 animations:^{
        
        [_pickView setOriginY:ScreenHeight-64];
    }];
    
}
- (NSString *)stringFromDate:(NSDate *)date{
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    
    //zzz表示时区，zzz可以删除，这样返回的日期字符将不包含时区信息。
    
    [dateFormatter setDateFormat:@"yyyy/MM/dd HH:mm"];
    
    NSString *destDateString = [dateFormatter stringFromDate:date];
    
    return destDateString;
}
- (NSString *)stringFromYearDate:(NSDate *)date{
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    
    //zzz表示时区，zzz可以删除，这样返回的日期字符将不包含时区信息。
    
    [dateFormatter setDateFormat:@"yyyy/MM/dd"];
    
    NSString *destDateString = [dateFormatter stringFromDate:date];
    
    return destDateString;
}

@end
